package com.cong.security.app.authentication;

import com.cong.security.core.properties.OAuth2ClientProperties;
import com.cong.security.core.properties.SecurityProperties;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.builders.InMemoryClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableAuthorizationServer
public class MyAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired(required = false)
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private TokenStore tokenStore;

    @Autowired(required = false)
    private TokenEnhancer jwtTokenEnhancer;

    @Autowired(required = false)
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore).authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService);
        if (jwtAccessTokenConverter != null && jwtTokenEnhancer != null) {
            // 增强器链
            TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
            List<TokenEnhancer> enhancers = new ArrayList<>();
            enhancers.add(jwtTokenEnhancer);
            enhancers.add(jwtAccessTokenConverter);
            tokenEnhancerChain.setTokenEnhancers(enhancers);
            endpoints.tokenEnhancer(tokenEnhancerChain).accessTokenConverter(jwtAccessTokenConverter);
        }
    }

    @Override
    @SuppressWarnings("deprecation")
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.tokenKeyAccess("permitAll()");
        security.checkTokenAccess("isAuthenticated()");
        security.allowFormAuthenticationForClients();
        // 解决Encoded password does not look like BCrypt报错
        // 因为springsecurity在最新版本升级后,默认把之前的明文密码方式给去掉了
        // https://spring.io/blog/2017/11/01/spring-security-5-0-0-rc1-released#password-storage-updated
        security.passwordEncoder(NoOpPasswordEncoder.getInstance());
}

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // 可以给哪些应用发放令牌
        // 可以存储在内存中,也可以存储在数据库中JdbcClientDetailsServiceBuilder----->clients.jdbc(dataSource)
        InMemoryClientDetailsServiceBuilder builder = clients.inMemory();
        if (ArrayUtils.isNotEmpty(securityProperties.getOAuth2().getClients())) {
            for (OAuth2ClientProperties config : securityProperties.getOAuth2().getClients()) {
                builder.withClient(config.getClientId()).secret(config.getClientSecret())// 设置client-id以及client-secret
                        .accessTokenValiditySeconds(config.getAccessTokenValiditySeconds())// 设置token过期时间，单位S
                        .refreshTokenValiditySeconds(config.getAccessTokenValiditySeconds() * 3) // 刷新token过期时间是token自身的三倍
                        .authorizedGrantTypes(config.getAuthorizedGrantTypes())// 支持的授权模式
                        .scopes(config.getScopes());// 可以发出去的权限
            }
        }
    }
}
